﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _07._01.FixedPointIteration
{
    class Program
    {
        static void Main(string[] args)
        {
            // x current
            // x1 new
            // x2 old
            double xNew, xOld = 0.0, xTerm;
            double small = 0.00001;
            int counter = 0;
            int maxIterations = 50;
            double relError = 0.0;
            double differenceG = 0.0;
            double differenceX = 0.0;
            double delta = 0.0;

            Console.WriteLine("Enter value for pTerm: ");

            xTerm = double.Parse(Console.ReadLine());
            xNew = G(xTerm);
            //do
            //{
            //    xOld = G(xNew);

            //    if (Math.Abs(xNew - xOld) < relErr)
            //    {
            //        break;
            //    }
            //    else
            //    {
            //        xNew = xOld;
            //    }

            //    counter++;
            //} while (counter <= maxIterations);

            while (counter <= maxIterations && relError >= small)
            {
                counter++;
                xOld = xTerm;
                xTerm = xNew;
                xNew = G(xTerm);
                differenceG = xNew - xTerm;
                delta = Math.Abs(differenceG);

                relError = (2 * delta) / (Math.Abs(xNew) + small);
            }

            differenceX = xTerm - xOld;
            double slope = differenceG / differenceX;

            Console.WriteLine("Root is {0}", xNew);
            Console.WriteLine("Consecutive iterates are within {0}", delta);

            if (Math.Abs(slope) > 1)
            {
                Console.WriteLine("The sequence appears to be diverging.");
            }
            else
            {
                Console.WriteLine("The sequence appears to be converging.");
            }
        }

        public static double G(double x)
        {
            return Math.Pow((x + 10), (double) 1 / 4); 
        }
    }
}
